"""
简历管理序列化器
"""
from rest_framework import serializers
from .models import (
    Resume, ResumeTemplate, ResumeSection, BasicInfo, Education,
    Skill, Project, WorkExperience, Award, SelfIntroduction, ResumeComment,
    ResumeGenerationRecord
)


class ResumeTemplateSerializer(serializers.ModelSerializer):
    """简历模板序列化器"""

    class Meta:
        model = ResumeTemplate
        fields = [
            'id', 'name', 'description', 'style_name', 'preview_image',
            'is_premium', 'is_recommended', 'is_active', 'usage_count',
            'sort_order', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'usage_count', 'created_at', 'updated_at']

    def validate_template_file(self, value):
        """验证模板文件"""
        if value:
            # 检查文件扩展名
            allowed_extensions = ['.doc', '.docx', '.pdf']
            file_extension = value.name.lower().split('.')[-1]

            if f'.{file_extension}' not in allowed_extensions:
                raise serializers.ValidationError(
                    f'不支持的文件格式。支持的格式: {", ".join(allowed_extensions)}'
                )

            # 检查文件大小 (20MB)
            if value.size > 20 * 1024 * 1024:
                raise serializers.ValidationError('模板文件大小不能超过20MB')

        return value

    def validate_preview_image(self, value):
        """验证预览图片"""
        if value:
            # 检查文件类型
            if not value.content_type.startswith('image/'):
                raise serializers.ValidationError('预览图必须是图片文件')

            # 检查文件大小 (5MB)
            if value.size > 5 * 1024 * 1024:
                raise serializers.ValidationError('预览图大小不能超过5MB')

        return value


class BasicInfoSerializer(serializers.ModelSerializer):
    """基本信息序列化器"""

    class Meta:
        model = BasicInfo
        fields = [
            'id', 'name', 'gender', 'birth_date', 'phone', 'email', 'address',
            'avatar', 'job_intention', 'expected_salary', 'work_location',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']


class EducationSerializer(serializers.ModelSerializer):
    """教育背景序列化器"""

    # 自定义日期字段，支持YYYY-MM格式
    start_date = serializers.CharField(max_length=7, help_text="格式：YYYY-MM")
    end_date = serializers.CharField(max_length=7, required=False, allow_blank=True, help_text="格式：YYYY-MM")

    class Meta:
        model = Education
        fields = [
            'id', 'school_name', 'major', 'degree', 'start_date', 'end_date',
            'is_current', 'gpa', 'description', 'order'
        ]
        read_only_fields = ['id']

    def validate_start_date(self, value):
        """验证开始日期格式"""
        if not value:
            raise serializers.ValidationError("开始日期不能为空")

        try:
            # 验证YYYY-MM格式
            from datetime import datetime
            datetime.strptime(value, '%Y-%m')
            return value
        except ValueError:
            raise serializers.ValidationError("日期格式错误，请使用YYYY-MM格式")

    def validate_end_date(self, value):
        """验证结束日期格式"""
        if not value:
            return value

        try:
            # 验证YYYY-MM格式
            from datetime import datetime
            datetime.strptime(value, '%Y-%m')
            return value
        except ValueError:
            raise serializers.ValidationError("日期格式错误，请使用YYYY-MM格式")

    def create(self, validated_data):
        """创建教育背景时转换日期格式"""
        # 转换日期格式
        if validated_data.get('start_date'):
            validated_data['start_date'] = f"{validated_data['start_date']}-01"

        if validated_data.get('end_date'):
            validated_data['end_date'] = f"{validated_data['end_date']}-01"

        return super().create(validated_data)

    def update(self, instance, validated_data):
        """更新教育背景时转换日期格式"""
        # 转换日期格式
        if validated_data.get('start_date'):
            validated_data['start_date'] = f"{validated_data['start_date']}-01"

        if validated_data.get('end_date'):
            validated_data['end_date'] = f"{validated_data['end_date']}-01"

        return super().update(instance, validated_data)

    def to_representation(self, instance):
        """序列化时将日期转换为YYYY-MM格式"""
        data = super().to_representation(instance)

        # 将日期字段转换为YYYY-MM格式
        if data.get('start_date'):
            data['start_date'] = data['start_date'][:7]  # 取前7位 YYYY-MM

        if data.get('end_date'):
            data['end_date'] = data['end_date'][:7]  # 取前7位 YYYY-MM

        return data


class SkillSerializer(serializers.ModelSerializer):
    """技能序列化器"""
    
    class Meta:
        model = Skill
        fields = ['id', 'name', 'level', 'description', 'order']
        read_only_fields = ['id']


class ProjectSerializer(serializers.ModelSerializer):
    """项目经验序列化器"""

    # 自定义日期字段，支持YYYY-MM格式
    start_date = serializers.CharField(max_length=7, help_text="格式：YYYY-MM")
    end_date = serializers.CharField(max_length=7, required=False, allow_blank=True, help_text="格式：YYYY-MM")

    class Meta:
        model = Project
        fields = [
            'id', 'name', 'start_date', 'end_date', 'is_current',
            'company_or_organization', 'overview', 'role', 'responsibilities',
            'problems_and_summary', 'description', 'technologies', 'achievements', 'url', 'order'
        ]
        read_only_fields = ['id']

    def validate_start_date(self, value):
        """验证开始日期格式"""
        if not value:
            raise serializers.ValidationError("开始日期不能为空")

        try:
            from datetime import datetime
            datetime.strptime(value, '%Y-%m')
            return value
        except ValueError:
            raise serializers.ValidationError("日期格式错误，请使用YYYY-MM格式")

    def validate_end_date(self, value):
        """验证结束日期格式"""
        if not value:
            return value

        try:
            from datetime import datetime
            datetime.strptime(value, '%Y-%m')
            return value
        except ValueError:
            raise serializers.ValidationError("日期格式错误，请使用YYYY-MM格式")

    def create(self, validated_data):
        """创建项目经验时转换日期格式"""
        if validated_data.get('start_date'):
            validated_data['start_date'] = f"{validated_data['start_date']}-01"

        if validated_data.get('end_date'):
            validated_data['end_date'] = f"{validated_data['end_date']}-01"

        return super().create(validated_data)

    def update(self, instance, validated_data):
        """更新项目经验时转换日期格式"""
        if validated_data.get('start_date'):
            validated_data['start_date'] = f"{validated_data['start_date']}-01"

        if validated_data.get('end_date'):
            validated_data['end_date'] = f"{validated_data['end_date']}-01"

        return super().update(instance, validated_data)

    def to_representation(self, instance):
        """序列化时将日期转换为YYYY-MM格式"""
        data = super().to_representation(instance)

        if data.get('start_date'):
            data['start_date'] = data['start_date'][:7]

        if data.get('end_date'):
            data['end_date'] = data['end_date'][:7]

        return data


class WorkExperienceSerializer(serializers.ModelSerializer):
    """工作经验序列化器"""

    # 自定义日期字段，支持YYYY-MM格式
    start_date = serializers.CharField(max_length=7, help_text="格式：YYYY-MM")
    end_date = serializers.CharField(max_length=7, required=False, allow_blank=True, help_text="格式：YYYY-MM")

    class Meta:
        model = WorkExperience
        fields = [
            'id', 'company_name', 'position_name', 'start_date', 'end_date',
            'is_current', 'job_responsibilities', 'position', 'description', 'achievements', 'order'
        ]
        read_only_fields = ['id']

    def validate_start_date(self, value):
        """验证开始日期格式"""
        if not value:
            raise serializers.ValidationError("开始日期不能为空")

        try:
            from datetime import datetime
            datetime.strptime(value, '%Y-%m')
            return value
        except ValueError:
            raise serializers.ValidationError("日期格式错误，请使用YYYY-MM格式")

    def validate_end_date(self, value):
        """验证结束日期格式"""
        if not value:
            return value

        try:
            from datetime import datetime
            datetime.strptime(value, '%Y-%m')
            return value
        except ValueError:
            raise serializers.ValidationError("日期格式错误，请使用YYYY-MM格式")

    def create(self, validated_data):
        """创建工作经验时转换日期格式"""
        if validated_data.get('start_date'):
            validated_data['start_date'] = f"{validated_data['start_date']}-01"

        if validated_data.get('end_date'):
            validated_data['end_date'] = f"{validated_data['end_date']}-01"

        return super().create(validated_data)

    def update(self, instance, validated_data):
        """更新工作经验时转换日期格式"""
        if validated_data.get('start_date'):
            validated_data['start_date'] = f"{validated_data['start_date']}-01"

        if validated_data.get('end_date'):
            validated_data['end_date'] = f"{validated_data['end_date']}-01"

        return super().update(instance, validated_data)

    def to_representation(self, instance):
        """序列化时将日期转换为YYYY-MM格式"""
        data = super().to_representation(instance)

        if data.get('start_date'):
            data['start_date'] = data['start_date'][:7]

        if data.get('end_date'):
            data['end_date'] = data['end_date'][:7]

        return data


class AwardSerializer(serializers.ModelSerializer):
    """获奖证书序列化器"""

    # 明确指定证书照片为可选字段
    certificate_photo = serializers.ImageField(required=False, allow_null=True)

    class Meta:
        model = Award
        fields = [
            'id', 'award_name', 'award_level', 'certificate_photo', 'award_description',
            'date_received', 'name', 'issuer', 'description', 'certificate_file', 'order'
        ]
        read_only_fields = ['id']

    def validate_certificate_photo(self, value):
        """验证证书照片"""
        if value:
            # 检查文件类型
            if hasattr(value, 'content_type') and not value.content_type.startswith('image/'):
                raise serializers.ValidationError('证书照片必须是图片文件')

            # 检查文件大小 (5MB)
            if hasattr(value, 'size') and value.size > 5 * 1024 * 1024:
                raise serializers.ValidationError('证书照片大小不能超过5MB')

        return value


class SelfIntroductionSerializer(serializers.ModelSerializer):
    """自我介绍序列化器"""

    class Meta:
        model = SelfIntroduction
        fields = ['id', 'content', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at']

    def validate_content(self, value):
        """验证自我介绍内容"""
        if not value or not value.strip():
            raise serializers.ValidationError('自我介绍内容不能为空')

        # 去除空白字符后计算字数
        content_length = len(value.strip())

        if content_length < 100:
            raise serializers.ValidationError(f'自我介绍内容不能少于100字，当前{content_length}字')

        if content_length > 300:
            raise serializers.ValidationError(f'自我介绍内容不能超过300字，当前{content_length}字')

        return value.strip()


class ResumeSectionSerializer(serializers.ModelSerializer):
    """简历章节序列化器"""
    
    class Meta:
        model = ResumeSection
        fields = [
            'id', 'section_type', 'title', 'content', 'is_completed',
            'order', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']


class ResumeCommentSerializer(serializers.ModelSerializer):
    """简历评论序列化器"""
    commenter_name = serializers.CharField(source='commenter.username', read_only=True)
    
    class Meta:
        model = ResumeComment
        fields = [
            'id', 'section_type', 'content', 'is_resolved',
            'commenter', 'commenter_name', 'created_at'
        ]
        read_only_fields = ['id', 'commenter', 'commenter_name', 'created_at']


class ResumeDetailSerializer(serializers.ModelSerializer):
    """简历详情序列化器"""
    student_name = serializers.CharField(source='student.name', read_only=True)
    template_name = serializers.CharField(source='template.name', read_only=True)
    reviewer_name = serializers.CharField(source='reviewer.username', read_only=True)
    
    # 关联数据
    basic_info = BasicInfoSerializer(read_only=True)
    education_set = EducationSerializer(many=True, read_only=True)
    skill_set = SkillSerializer(many=True, read_only=True)
    project_set = ProjectSerializer(many=True, read_only=True)
    workexperience_set = WorkExperienceSerializer(many=True, read_only=True)
    award_set = AwardSerializer(many=True, read_only=True)
    selfintroduction = SelfIntroductionSerializer(read_only=True)
    resumesection_set = ResumeSectionSerializer(many=True, read_only=True)
    resumecomment_set = ResumeCommentSerializer(many=True, read_only=True)
    
    class Meta:
        model = Resume
        fields = [
            'id', 'student', 'student_name', 'resume_type', 'uploaded_file',
            'template', 'template_name', 'title', 'status', 'current_step',
            'completion_rate', 'reviewer', 'reviewer_name', 'review_date',
            'review_comments', 'generated_file', 'generated_file_url',
            'generated_file_name', 'generated_file_type', 'generated_at',
            # AI评估相关字段
            'ai_evaluation_status', 'ai_evaluation_file', 'ai_evaluation_content',
            'ai_evaluation_job_position', 'ai_evaluation_at', 'ai_evaluation_error',
            'created_at', 'updated_at',
            # 关联数据
            'basic_info', 'education_set', 'skill_set', 'project_set',
            'workexperience_set', 'award_set', 'selfintroduction',
            'resumesection_set', 'resumecomment_set'
        ]
        read_only_fields = [
            'id', 'student', 'student_name', 'template_name', 'reviewer_name',
            'completion_rate', 'ai_evaluation_status', 'ai_evaluation_file',
            'ai_evaluation_content', 'ai_evaluation_job_position', 'ai_evaluation_at',
            'ai_evaluation_error', 'created_at', 'updated_at'
        ]


class ResumeListSerializer(serializers.ModelSerializer):
    """简历列表序列化器"""
    student_name = serializers.CharField(source='student.name', read_only=True)
    template_name = serializers.CharField(source='template.name', read_only=True)
    completion_rate = serializers.SerializerMethodField()
    current_step = serializers.IntegerField(read_only=True)

    class Meta:
        model = Resume
        fields = [
            'id', 'student', 'student_name', 'resume_type', 'template',
            'template_name', 'title', 'status', 'completion_rate', 'current_step',
            'uploaded_file', 'generated_file', 'generated_file_url',
            'generated_file_name', 'generated_file_type', 'generated_at',
            # AI评估相关字段
            'ai_evaluation_status', 'ai_evaluation_file', 'ai_evaluation_at',
            'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'student', 'student_name', 'template_name',
            'ai_evaluation_status', 'ai_evaluation_file', 'ai_evaluation_at',
            'created_at', 'updated_at'
        ]

    def get_completion_rate(self, obj):
        """获取实时计算的完成度"""
        try:
            # 对于在线生成的简历，实时计算完成度
            if obj.resume_type == 'generated':
                return obj.calculate_actual_completion_rate()
            else:
                # 对于上传的简历，如果有文件就是100%，没有文件就是0%
                if obj.uploaded_file:
                    return 100.0
                else:
                    return 0.0
        except Exception as e:
            # 如果计算失败，返回数据库中的值
            return float(obj.completion_rate) if obj.completion_rate else 0.0


class ResumeCreateSerializer(serializers.ModelSerializer):
    """创建简历序列化器"""

    class Meta:
        model = Resume
        fields = ['id', 'title', 'resume_type', 'template']
        read_only_fields = ['id']
        
    def validate(self, data):
        """验证数据"""
        resume_type = data.get('resume_type')
        template = data.get('template')

        # 只在生成类型时验证模板，上传类型的文件通过单独接口处理
        if resume_type == 'generated' and not template:
            raise serializers.ValidationError('生成类型的简历必须选择模板')

        return data


class FileUploadSerializer(serializers.Serializer):
    """文件上传序列化器"""
    file = serializers.FileField()
    title = serializers.CharField(max_length=200, required=False)
    
    def validate_file(self, value):
        """验证文件类型"""
        allowed_extensions = ['.pdf', '.doc', '.docx']
        file_extension = value.name.lower().split('.')[-1]
        
        if f'.{file_extension}' not in allowed_extensions:
            raise serializers.ValidationError(
                f'不支持的文件格式。支持的格式: {", ".join(allowed_extensions)}'
            )
        
        # 检查文件大小 (10MB)
        if value.size > 10 * 1024 * 1024:
            raise serializers.ValidationError('文件大小不能超过10MB')

        return value


class ResumeGenerationRecordSerializer(serializers.ModelSerializer):
    """简历生成记录序列化器"""

    template_name = serializers.CharField(source='template.name', read_only=True)
    student_name = serializers.CharField(source='student.name', read_only=True)
    duration = serializers.ReadOnlyField()

    class Meta:
        model = ResumeGenerationRecord
        fields = [
            'id', 'title', 'format', 'status', 'template_name', 'student_name',
            'form_data', 'generated_file', 'error_message', 'duration',
            'created_at', 'started_at', 'completed_at'
        ]
        read_only_fields = [
            'id', 'status', 'generated_file', 'error_message', 'duration',
            'created_at', 'started_at', 'completed_at'
        ]


class ResumeGenerationRequestSerializer(serializers.Serializer):
    """简历生成请求序列化器"""

    template_id = serializers.IntegerField()
    title = serializers.CharField(max_length=200)
    format = serializers.ChoiceField(choices=['docx', 'pdf'], default='docx')

    # 基本信息
    name = serializers.CharField(max_length=100)
    phone = serializers.CharField(max_length=20)
    email = serializers.EmailField()
    school = serializers.CharField(max_length=200, required=False, allow_blank=True)
    major = serializers.CharField(max_length=100, required=False, allow_blank=True)
    introduction = serializers.CharField(required=False, allow_blank=True)

    # 头像文件
    avatar = serializers.ImageField(required=False, allow_null=True)

    def validate_template_id(self, value):
        """验证模板ID"""
        try:
            template = ResumeTemplate.objects.get(id=value, is_active=True)
            return value
        except ResumeTemplate.DoesNotExist:
            raise serializers.ValidationError('模板不存在或已禁用')

    def validate_avatar(self, value):
        """验证头像文件"""
        if value:
            # 检查文件大小 (2MB)
            if value.size > 2 * 1024 * 1024:
                raise serializers.ValidationError('头像文件大小不能超过2MB')

            # 检查文件格式
            allowed_formats = ['image/jpeg', 'image/png']
            if value.content_type not in allowed_formats:
                raise serializers.ValidationError('头像只支持JPG和PNG格式')

        return value
